/*
 * Copyright 2017 Zhihu Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zhihu.matisse.internal.ui;

import android.os.Bundle;

import androidx.annotation.Nullable;

import com.zhihu.matisse.internal.entity.SelectionSpec;
import com.zhihu.matisse.internal.ui.adapter.PreviewPagerFileAdapter;
import com.zhihu.matisse.internal.utils.PathUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FilePreviewActivity extends BasePreviewActivity {

    public static final String EXTRA_PATH = "extra_path";
    public static final String EXTRA_ITEM = "extra_item";

    private boolean mIsAlreadySetPosition;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!SelectionSpec.getInstance().hasInited) {
            setResult(RESULT_CANCELED);
            finish();
            return;
        }
        String path = getIntent().getStringExtra(EXTRA_PATH);
        initData(path);

        File item = (File) getIntent().getSerializableExtra(EXTRA_ITEM);
        if (mSpec.countable) {
            mCheckView.setCheckedNum(mSelectedFileCollection.checkedNumOf(item));
        } else {
            mCheckView.setChecked(mSelectedFileCollection.isSelected(item));
        }
        updateSize(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void initData(String path) {
        List<File> items = new ArrayList<>();
        // 得到该路径文件夹下所有的文件
        File fileAll = new File(path);
        File[] files = fileAll.listFiles();
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        if(files != null && files.length > 0){
            PathUtils.arraySort(files);
            for (File file : files) {
                if (PathUtils.isImage(file)) {
                    items.add(file);
                }
            }
        }
        if (items.isEmpty()) {
            return;
        }

        PreviewPagerFileAdapter adapter = (PreviewPagerFileAdapter) mPager.getAdapter();
        adapter.addAll(items);
        adapter.notifyDataSetChanged();
        if (!mIsAlreadySetPosition) {
            mIsAlreadySetPosition = true;
            File selected = (File) getIntent().getSerializableExtra(EXTRA_ITEM);
            int selectedIndex = items.indexOf(selected);
            mPager.setCurrentItem(selectedIndex, false);
            mPreviousPos = selectedIndex;
        }
    }

}
